import { createStore, useStore as baseUseStore, Store } from 'vuex';
import actions from './actions';
import mutations from './mutations';
import state from './state';
import { InjectionKey } from 'vue';
import { ArticleDTO, CommentUserInfo, UserDTO } from '@/bean/dto';
import getters from './getters';
import Cookies from 'js-cookie';
import { SET_USER_INFO } from './actiontype';
import { userService } from '@/api/user';
// import createPersistedState from "vuex-persistedstate"

// 手动声明 state 类型
export interface RootState {
  isMenuVisible: boolean;
  commentUserInfo: CommentUserInfo | null;
  hotList: null | ArticleDTO[];
  userInfo: null | UserDTO;
}
// 定义注入类型
export const key: InjectionKey<Store<RootState>> = Symbol();

const store = createStore<RootState>({
  // 这玩意如果很多的话,需要拆开来
  state,
  mutations,
  actions,
  getters,
  // plugins: [createPersistedState()]
});

// 定义自己的 `useStore` 组合式函数,hooks函数
export function useStore() {
  return baseUseStore(key);
}

export const checkAuthState = (): void => {
  const isLogined = Cookies.get('islogined');
  if (isLogined !== '1') {
    // islogined失效
    store.commit(SET_USER_INFO, null);
  } else {
    // islogined有效，获取最新user信息
    userService.current().then((res) => {
      store.commit(SET_USER_INFO, res.data);
    });
  }
};

// 初始化时检查一次
checkAuthState();

export default store;
